from app import db
from datetime import datetime
import uuid
import random
import string

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(128), nullable=False)  # 直接存储明文密码
    nickname = db.Column(db.String(50), unique=True)
    phone = db.Column(db.String(20), unique=True)
    email = db.Column(db.String(100), unique=True)
    avatar = db.Column(db.String(255))
    gender = db.Column(db.String(10))
    age = db.Column(db.Integer)
    driving_years = db.Column(db.Integer)  # 车龄
    city = db.Column(db.String(50))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 销售记录关联
    sales = db.relationship('Sales', backref='salesperson', lazy=True)
    
    def verify_password(self, password):
        """验证密码（明文比较）"""
        return self.password == password
    
    @staticmethod
    def generate_nickname():
        """生成随机昵称"""
        random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
        return f"{random_str}_user"
    
    def __init__(self, username, password, **kwargs):
        self.username = username
        self.password = password
        
        # 如果没有提供昵称，生成一个随机昵称
        if 'nickname' not in kwargs or not kwargs['nickname']:
            self.nickname = self.generate_nickname()
        else:
            self.nickname = kwargs.get('nickname')
            
        self.phone = kwargs.get('phone')
        self.email = kwargs.get('email')
        self.avatar = kwargs.get('avatar')
        self.gender = kwargs.get('gender')
        self.age = kwargs.get('age')
        self.driving_years = kwargs.get('driving_years')
        self.city = kwargs.get('city')
    
    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'nickname': self.nickname,
            'phone': self.phone,
            'email': self.email,
            'avatar': self.avatar,
            'gender': self.gender,
            'age': self.age,
            'driving_years': self.driving_years,
            'city': self.city,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }